import React, { useState, useEffect, useCallback } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import styled from 'styled-components';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import backIcon from '../assets/images/back-icon.png';

// API 返回结果的通用结构 (根据您提供的 Result<T>)
interface ApiResponse<T> {
  data: T | null; // data 可能是 null
  code: number;   // 状态码，200 成功
  message: string; // 提示信息
}

// 用户信息状态的结构，我们将API返回的名字包装一下
interface UserProfile {
  id: string;    // 用户ID，从组件状态获取
  name: string;  // 用户名，从API获取
}

// 心情数据结构 (根据您的 MoodVO)
interface MoodEntry {
  mood: number; // 1.开心2.难过3.愤怒4.平静5.困惑6.焦虑7.开悟
  date: string; // LocalDate 通常是 YYYY-MM-DD 格式的字符串
}

// 将心情编号映射到文本描述
const moodMap: { [key: number]: string } = {
  1: '开心 😊',
  2: '难过 😢',
  3: '愤怒 😠',
  4: '平静 😌',
  5: '困惑 🤔',
  6: '焦虑 😟',
  7: '开悟 ✨',
};

// Map mood ID to a display score for the Y-axis of the chart
const moodDisplayScoreMap: { [key: number]: number } = {
  1: 5, // 开心 -> 积极
  2: 1, // 难过 -> 低落
  3: 1, // 愤怒 -> 低落
  4: 3, // 平静 -> 平静
  5: 2, // 困惑 -> 介于低落和平静之间
  6: 1, // 焦虑 -> 低落
  7: 5, // 开悟 -> 积极
};

// Labels for the Y-axis ticks based on display scores
const scoreToLabelMap: { [key: number]: string } = {
  1: '低落',
  3: '平静',
  5: '积极',
};

// Framer Motion Variants
const pageVariants = {
  initial: { opacity: 0 },
  in: { opacity: 1, transition: { staggerChildren: 0.1, duration: 0.4 } },
  out: { opacity: 0 }
};

const cardVariants = {
  initial: { opacity: 0, y: 30, scale: 0.98 },
  in: { opacity: 1, y: 0, scale: 1, transition: { duration: 0.5, ease: [0.25, 1, 0.5, 1] } }, // smoother ease
  out: { opacity: 0, y: -20, scale: 0.95 }
};

// Styled Components
const PageContainer = styled(motion.div)`
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #e0f7fa 0%, #b3e5fc 100%); // Light, airy blue gradient
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  padding-top: 90px; // Increased for fixed header
  box-sizing: border-box;
  position: relative;
  font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif; // Modern font stack
`;

const Header = styled(motion.header)`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  padding: 20px 0; // Slightly more padding
  background-color: rgba(255, 255, 255, 0.65); // More transparent
  backdrop-filter: blur(12px); // Stronger blur
  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.07); // Softer shadow
  z-index: 1000;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
`;

const BackButton = styled(motion.img)`
  position: absolute;
  left: 25px;
  top: 50%;
  transform: translateY(-50%);
  width: 22px;
  height: 22px;
  cursor: pointer;
  opacity: 0.7;
  transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;

  &:hover {
    opacity: 1;
    transform: translateY(-50%) scale(1.1);
  }
`;

const Title = styled(motion.h1)`
  font-size: 1.5rem;
  color: #2c3e50; // Darker, more grounded blue
  font-weight: 500;
  margin: 0;
`;

const ContentWrapper = styled(motion.div)`
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 650px; // Slightly narrower for better focus
  gap: 28px; // Increased gap
`;

const InfoCard = styled(motion.section)`
  background: rgba(255, 255, 255, 0.55); // Slightly more opaque
  backdrop-filter: blur(15px); // Enhanced blur
  border-radius: 18px; // Softer radius
  padding: 28px; // More padding
  width: 100%;
  box-shadow: 0 10px 35px rgba(0, 0, 0, 0.08); // More pronounced shadow
  
  h2 {
    font-size: 1.25rem; // Adjusted size
    color: #34495e; // Consistent with Title's family
    margin-top: 0;
    margin-bottom: 22px;
    border-bottom: 1px solid rgba(52, 73, 94, 0.1); // Subtle border
    padding-bottom: 12px;
    font-weight: 500;
  }
  p {
    font-size: 0.95rem; // Fine-tuned size
    color: #5a6a7a; // Softer text color
    line-height: 1.65;
  }
  strong {
    color: #2c3e50; // Consistent strong color
    font-weight: 500;
  }
`;

const ButtonContainer = styled(motion.div)`
  width: 100%;
  display: flex;
  justify-content: center;
`;

const StyledButton = styled(motion.button)`
  padding: 12px 28px;
  font-size: 0.95rem;
  color: white;
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  border: none;
  border-radius: 25px; // Pill shape
  cursor: pointer;
  font-weight: 500;
  box-shadow: 0 5px 15px rgba(0, 123, 255, 0.25);
  transition: all 0.25s cubic-bezier(0.25, 1, 0.5, 1); // Smooth transition

  &:hover:not(:disabled) {
    transform: translateY(-3px) scale(1.03);
    box-shadow: 0 8px 20px rgba(0, 123, 255, 0.3);
  }
  &:active:not(:disabled) {
    transform: translateY(-1px) scale(0.98);
  }
  &:disabled {
    background: #bdc3c7; // Softer disabled color
    cursor: not-allowed;
    box-shadow: none;
    transform: none;
  }
`;

const MoodList = styled.ul`
  list-style-type: none;
  padding-left: 0;
  li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding: 12px 15px; // More padding
    border-bottom: 1px solid rgba(0,0,0,0.06);
    font-size: 0.9rem;
    color: #4a5568; // Text color from Welcome.tsx
    border-radius: 8px; // Rounded list items
    transition: background-color 0.2s ease;
    &:last-child {
      border-bottom: none;
    }
    &:hover {
      background-color: rgba(0,0,0,0.025); // Subtle hover
    }
  }
`;

const ChartContainer = styled.div`
  margin-top: 25px; // More space above chart
  height: 320px; // Slightly taller
  width: 100%;
`;

const ErrorDisplay = styled(motion.div)`
  color: #c0392b; // Standard error red
  background-color: rgba(231, 76, 60, 0.08); // Very subtle background
  width: 100%;
  max-width: 650px;
  margin-bottom: 25px;
  padding: 18px 22px;
  border: 1px solid rgba(192, 57, 43, 0.2); // Lighter border
  border-radius: 12px; // Softer radius
  white-space: pre-wrap;
  text-align: center;
  font-size: 0.9rem;
`;

const LoadingDisplay = styled(motion.div)`
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 90px - 40px); // Full available height minus header and padding
  font-size: 1.2rem;
  color: #007bff; // Theme color
  width: 100%;
`;

const MyPage: React.FC = () => {
  const navigate = useNavigate();
  const [userId, setUserId] = useState<string>(''); // 初始为空
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [moodHistory, setMoodHistory] = useState<MoodEntry[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    } else {
      console.warn('用户ID未找到，请先登录');
      setError('用户ID未找到，请先登录');
      setLoading(false); // Ensure loading is false to show error message correctly
    }
  }, []); // 空依赖数组，仅在组件挂载时运行一次

  // 获取用户昵称等信息
  const fetchUserData = useCallback(async (currentUserId: string) => {
    setError(null); // 重置特定于此获取的错误
    try {
      const response = await fetch(`http://localhost:8111/api/get/${currentUserId}`, {
        method: 'POST',
        // headers: { 'Content-Type': 'application/json', }, // 如果后端严格需要
        // body: JSON.stringify({}), // 如果后端严格需要
      });

      if (!response.ok) {
        let errorMsg = `HTTP error! status: ${response.status}`;
        try {
            const errorResult: ApiResponse<null> = await response.json();
            if (errorResult && errorResult.message) {
                errorMsg = errorResult.message;
            }
        } catch (jsonError) { /* Do nothing, use base errorMsg */ }
        throw new Error(errorMsg);
      }

      const result: ApiResponse<string> = await response.json(); // API响应的data是string
      
      if (result.code === 200 && typeof result.data === 'string') {
        setUserProfile({ id: currentUserId, name: result.data });
      } else if (result.code === 200 && result.data === null) { // 后端成功返回，但名字是null
        throw new Error('获取到的用户名数据为空 (null)');
      } else if (result.code === 200 && typeof result.data !== 'string') { // 后端成功返回，但data不是字符串
        throw new Error('获取到的用户名数据格式不正确，期望字符串但收到其他类型');
      } else { // code 不是 200
        throw new Error(result.message || '获取用户信息失败 (未知原因)');
      }
    } catch (e: any) {
      console.error('获取用户信息操作失败:', e);
      setError((prev) => prev ? `${prev}\n获取昵称失败: ${e.message}` : `获取昵称失败: ${e.message}`);
      setUserProfile(null); 
    }
  }, []);

  // 获取用户心情记录
  const fetchMoodHistory = useCallback(async (currentUserId: string) => {
    // setError(null); // 如果希望错误是独立的，可以取消注释
    try {
      const response = await fetch(`http://localhost:8111/api/getMoodByUserId/${currentUserId}`, {
        method: 'POST',
      });

      if (!response.ok) {
        let errorMsg = `HTTP error! status: ${response.status}`;
        try {
            const errorResult: ApiResponse<null> = await response.json();
            if (errorResult && errorResult.message) {
                errorMsg = errorResult.message;
            }
        } catch (jsonError) { /* Do nothing */ }
        throw new Error(errorMsg);
      }

      const result: ApiResponse<MoodEntry[]> = await response.json();

      if (result.code === 200 && result.data) {
        setMoodHistory(result.data);
      } else if (result.code === 200 && result.data === null) {
        // 如果允许心情记录为空，则可以设置为空数组，否则视为错误或提示
        setMoodHistory([]); 
        // 或者 throw new Error('心情记录数据为空 (null)');
      } else {
        throw new Error(result.message || '获取心情记录失败 (未知原因)');
      }
    } catch (e: any) {
      console.error('获取心情记录操作失败:', e);
      setError((prevError) => prevError ? `${prevError}\n获取心情记录失败: ${e.message}` : `获取心情记录失败: ${e.message}`);
      setMoodHistory([]); 
    }
  }, []);

  useEffect(() => {
    const loadAllData = async () => {
      setLoading(true);
      setError(null); // 重置页面加载时的错误状态
      
      // 确保 userId 存在后再调用API
      if (userId) {
        await fetchUserData(userId); 
        await fetchMoodHistory(userId);
      }
      
      setLoading(false);
    };
    // 仅当 userId 有效时才加载数据
    if (userId) {
      loadAllData();
    }
  }, [userId, fetchUserData, fetchMoodHistory]); // fetchUserData, fetchMoodHistory 作为依赖

  const handleEditProfile = async () => {
    const currentUsername = userProfile?.name || '';
    const newUsername = prompt('请输入新的昵称:', currentUsername);

    if (newUsername && newUsername.trim() !== '' && newUsername.trim() !== currentUsername) {
      try {
        setLoading(true); // 开始编辑操作，显示加载状态
        const response = await fetch(`http://localhost:8111/api/update`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ userId: userId, username: newUsername.trim() }), // DTO 需要 username
        });

        if (!response.ok) {
          let errorMsg = `HTTP error! status: ${response.status}`;
          try {
              const errorResult: ApiResponse<null> = await response.json();
              if (errorResult && errorResult.message) {
                  errorMsg = errorResult.message;
              }
          } catch (jsonError) { /* Do nothing */ }
          throw new Error(errorMsg);
        }

        const resultUpdate: ApiResponse<any> = await response.json(); 
        if (resultUpdate.code === 200) {
          alert('昵称更新成功!');
          // 更新本地状态以立即反映更改
          setUserProfile(prevProfile => prevProfile ? { ...prevProfile, name: newUsername.trim() } : null);
          // 如果更新API也返回了更新后的用户名，可以直接使用那个数据
          // 或者, 如果需要完全确认, 可以重新调用 fetchUserData(userId);
        } else {
          throw new Error(resultUpdate.message || '更新昵称操作失败');
        }
      } catch (e: any) {
        console.error('更新昵称操作失败:', e);
        alert(`更新昵称失败: ${e.message}`);
        setError((prevError) => prevError ? `${prevError}\n更新昵称失败: ${e.message}` : `更新昵称失败: ${e.message}`);
      } finally {
        setLoading(false); // 结束编辑操作，隐藏加载状态
      }
    }
  };

  // Prepare data for the chart
  const chartData = moodHistory
    .map(entry => ({
      date: entry.date,
      originalMood: entry.mood,
      moodName: moodMap[entry.mood] || `未知 (${entry.mood})`,
      displayScore: moodDisplayScoreMap[entry.mood] || 0
    }))
    .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());

  // Custom Tooltip for the chart
  const CustomTooltip = ({ active, payload, label }: any) => {
    if (active && payload && payload.length) {
      return (
        <div style={{
          backgroundColor: 'rgba(255, 255, 255, 0.85)', // Slightly more opaque for readability
          padding: '12px', // Increased padding
          border: '1px solid rgba(0,0,0,0.08)', // Softer border
          borderRadius: '10px', // Consistent rounding
          boxShadow: '0 4px 12px rgba(0,0,0,0.08)' // Softer shadow
        }}>
          <p style={{ margin: 0, color: '#2c3e50', fontSize: '0.85em', marginBottom: '4px' }}>{`日期 : ${label}`}</p>
          <p style={{ margin: '0', color: payload[0].stroke || '#8884d8', fontSize: '0.9em', fontWeight: '500' }}>
            {`心情 : ${payload[0].payload.moodName}`}
          </p>
        </div>
      );
    }
    return null;
  };

  if (loading && !userProfile && moodHistory.length === 0 && !error) {
    return (
      <PageContainer initial="initial" animate="in" exit="out" variants={pageVariants}>
        <Header initial={{ y: -60, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ duration: 0.5, ease: "easeOut" }}>
          <BackButton 
            src={backIcon} 
            alt="Back" 
            onClick={() => navigate(-1)} 
            whileHover={{ scale: 1.15, opacity: 0.9 }}
            transition={{ duration: 0.2 }}
          />
          <Title>我的主页</Title>
        </Header>
        <LoadingDisplay variants={cardVariants}>正在加载您的信息...</LoadingDisplay>
      </PageContainer>
    );
  }

  return (
    <PageContainer initial="initial" animate="in" exit="out" variants={pageVariants}>
      <Header initial={{ y: -60, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ duration: 0.5, ease: "easeOut", delay: 0.1 }}>
        <BackButton 
          src={backIcon} 
          alt="Back" 
          onClick={() => navigate(-1)} 
          whileHover={{ scale: 1.15, opacity: 0.9 }}
          transition={{ duration: 0.2 }}
        />
        <Title>我的主页</Title>
      </Header>

      <ContentWrapper variants={cardVariants}>
        <AnimatePresence>
          {error && (
            <ErrorDisplay
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10, transition: { duration: 0.2 }}}
            >
              错误信息:\n{error}
            </ErrorDisplay>
          )}
        </AnimatePresence>

        <InfoCard variants={cardVariants}>
          <h2>我的信息</h2>
          {userProfile && userProfile.name ? (
            <p><strong>昵称:</strong> {userProfile.name}</p>
          ) : (
            !loading && <p>未能加载用户昵称。</p>
          )}
        </InfoCard>

        <ButtonContainer variants={cardVariants}>
          <StyledButton
            onClick={handleEditProfile}
            disabled={!userProfile || loading}
            whileHover={{ scale: (!userProfile || loading) ? 1 : 1.05 }}
            whileTap={{ scale: (!userProfile || loading) ? 1 : 0.95 }}
          >
            修改个人资料
          </StyledButton>
        </ButtonContainer>

        <InfoCard variants={cardVariants}>
          <h2>情绪趋势概览</h2>
          {moodHistory.length > 0 ? (
            <>
              <MoodList>
                {chartData.map((moodEntry, index) => ( // Use chartData to ensure sorted order if needed, or moodHistory directly
                  <li key={index}>
                    <span>{moodEntry.date}</span>
                    <span>{moodEntry.moodName}</span>
                  </li>
                ))}
              </MoodList>
              <ChartContainer>
                <ResponsiveContainer>
                  <LineChart
                    data={chartData}
                    margin={{
                      top: 5,
                      right: 20, // Adjusted for better spacing
                      left: -10, // Adjusted for tick labels
                      bottom: 5,
                    }}
                  >
                    <CartesianGrid strokeDasharray="3 3" stroke="rgba(0,0,0,0.1)" />
                    <XAxis dataKey="date" stroke="#667788" fontSize="11px" />
                    <YAxis
                      stroke="#667788"
                      fontSize="11px"
                      domain={[1, 5]}
                      ticks={[1, 3, 5]}
                      tickFormatter={(score: number) => scoreToLabelMap[score] || score.toString()}
                    />
                    <Tooltip content={<CustomTooltip />} animationEasing="ease-out" animationDuration={300}/>
                    <Legend 
                      formatter={(value: string) => <span style={{color: '#333', fontSize: '13px'}}>心情趋势</span>}
                      wrapperStyle={{paddingTop: '15px'}}
                    />
                    <Line 
                      type="monotone" 
                      dataKey="displayScore" 
                      stroke="#007bff" 
                      strokeWidth={2} 
                      activeDot={{ r: 7, strokeWidth: 2, fill: '#fff', stroke: '#007bff' }} 
                      name="心情趋势" 
                      dot={{r: 3, fill: '#007bff'}}
                    />
                  </LineChart>
                </ResponsiveContainer>
              </ChartContainer>
            </>
          ) : (
            !loading && <p>暂无心情记录，或加载失败。</p>
          )}
        </InfoCard>
      </ContentWrapper>
    </PageContainer>
  );
};

export default MyPage;
